/*
 * @Author: vinny
 * @Date: 2024-09-01 17:34:23
 * @Desc: localStorage
 */
class Storage {
    constructor(name = import.meta.env.VITE_LOCAL_STORAGE_KEY_PREFIX) {
        this.name = name;
        this.init();
    }
    name;
    init() {
        Object.keys(localStorage).forEach((item) => {
            if (item.startsWith(this.name)) {
                this.hasItem(item.replace(this.name, ''));
            }
        });
    }
    /**
     * localStorage存储
     * @param key 存储名称
     * @param value 存储值
     * @param time 存储时间
     */
    setItem(key, value, time) {
        if (value === undefined)
            value = null;
        const _key = this.name + key;
        const _value = { value };
        time && (_value.time = time * 1000 + new Date().getTime());
        localStorage.setItem(_key, JSON.stringify(_value));
    }
    /**
     *  获取会话
     * @param key 存储名称
     * @returns
     */
    getItem(key) {
        if (this.hasItem(key)) {
            const item = localStorage.getItem(this.name + key);
            if (item !== null) {
                return JSON.parse(item).value;
            }
        }
        return null;
    }
    /**
     * 删除会话
     * @param key 存储名称
     */
    removeItem(key) {
        localStorage.removeItem(this.name + key);
    }
    /**
     * 清空所有会话
     */
    clear() {
        Object.keys(localStorage).forEach((item) => {
            if (item.startsWith(this.name)) {
                localStorage.removeItem(item);
            }
        });
    }
    /**
     * 所有会话长度
     */
    getLength() {
        return Object.keys(localStorage).length;
    }
    /**
     * 判断是否存在某个会话，当前时间>存储时间删除会话
     */
    hasItem(key) {
        const _key = this.name + key;
        if (localStorage.getItem(_key)) {
            const item = localStorage.getItem(_key);
            if (item !== null) {
                const _time = JSON.parse(item).time;
                if (new Date().getTime() > _time) {
                    localStorage.removeItem(_key);
                    return false;
                }
                return true;
            }
            else {
                return false;
            }
        }
    }
}
export default Storage;
